﻿using System.Collections.Generic;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Domain.Wrappers;

namespace Cms.Application.Admin.Presenters
{
    public class DashboardGadgetsPresenter : BasePresenter
    {
        private readonly IDashboardGadgetsView _view;
        private readonly Administrator _administrator;

        public IDiskAccess DiskAccess { get; set; }

        public DashboardGadgetsPresenter(IDashboardGadgetsView view)
            : this(view, new RepositoryFactory())
        {
            DiskAccess = new DiskAccess();
        }
        
        public DashboardGadgetsPresenter(IDashboardGadgetsView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            if (!_administrator.HasPermission.DashboardGadgets)
                _view.RedirectToPermissionDeniedPage();
        }
        
        public void Initialize()
        {
            SetGadgets();
        }
        
        public void SetGadgets()
        {
            DashboardGadgetHandler.SyncGadgets(SystemRepository);

            IList<DashboardGadgetDescription> gadgetDescriptions = new List<DashboardGadgetDescription>();
            IList<DashboardGadget> gadgets = SystemRepository.GetDashboardGadgets();
            foreach (DashboardGadget gadget in gadgets)
            {
                string className = gadget.Filename.Substring(0, gadget.Filename.ToLower().LastIndexOf(".ascx"));
                string name = Translator.GetText("Admin/Translations/DashboardGadgets/" + className + ".xml", "GadgetName", _view.Localization);
                string description = Translator.GetText("Admin/Translations/DashboardGadgets/" + className + ".xml", "GadgetDescription", _view.Localization);
                gadgetDescriptions.Add(new DashboardGadgetDescription(name, description, gadget));
            }
            _view.SetGadgets(gadgetDescriptions);
        }

        public void DeleteCustomGadget(int id)
        {
            DashboardGadget gadget = SystemRepository.GetDashboardGadget(id);
            DiskAccess.DeleteFile("Admin\\DashboardGadgets\\" + gadget.Filename);
            DiskAccess.DeleteFile("Admin\\Translations\\DashboardGadgets\\" +
                          gadget.Filename.Substring(0, gadget.Filename.ToLower().LastIndexOf(".ascx")) + ".xml");
            SystemRepository.DeleteDashboardGadget(id);
            SetGadgets();
        }
    }
}